//
//  WLRefreshControl.swift
//  WLWeibo
//
//  Created by Devil on 16/8/15.
//  Copyright © 2016年 Wiliam. All rights reserved.
//

import UIKit

enum WLRefreshControlState: Int {
    case Normal = 0
    case Pulling = 1
    case Refeshing = 2
}

private let WLRefreshControlH: CGFloat = 50

class WLRefreshControl: UIControl {
    //记录滑动视图
    var scrollView:UIScrollView?
    //记录状态
    var hmState:WLRefreshControlState = .Normal{
    
        didSet{
        
            switch hmState {
            case .Normal:
                messageLabel.text = "正常"
                UIView.animateWithDuration(0.25, animations: { 
                    self.pullImageView.transform = CGAffineTransformIdentity
                })
                
                if oldValue == .Refeshing {
                    UIView.animateWithDuration(0.25, animations: { 
                        self.scrollView?.contentInset.top -= WLRefreshControlH
                        }, completion: { (_) in
                            //结束动画
                            self.activityView.stopAnimating()
                            self.pullImageView.hidden = false
                    })
                }
                
            case .Pulling:
                messageLabel.text = "下拉中"
                UIView.animateWithDuration(0.25, animations: { 
                    self.pullImageView.transform = CGAffineTransformMakeRotation(CGFloat(-3*M_PI))
                })
            case .Refeshing:
                messageLabel.text = "刷新中"
                UIView.animateWithDuration(0.25, animations: { 
                    self.scrollView?.contentInset.top += WLRefreshControlH
                    }, completion: { (_) in
                        self.pullImageView.hidden = true
                        //开始动画
                        self.activityView.startAnimating()
                        //告知外界刷新
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
            }
        
        }
    
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -WLRefreshControlH, width: SCREENW, height: WLRefreshControlH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //结束刷新  供外界使用
    func endRefreshing(){
        hmState = .Normal
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        //判断是否为nil
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        //赋值
        self.scrollView = scrollView
        //使用KVO 注册观察者
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //记录scrollView滚动
        let contentOffsetY = self.scrollView!.contentOffset.y
        //顶部滑动的距离
        let contentInsetTop = self.scrollView!.contentInset.top
        //代表拖动中
        if scrollView!.dragging {
            if contentOffsetY > -contentInsetTop - WLRefreshControlH && hmState == .Pulling {
                print("正常")
                hmState = .Normal
            }else if contentOffsetY <= -contentInsetTop - WLRefreshControlH && hmState == .Normal {
                print("正常")
                hmState = .Pulling
        }
        }else {
        
            if hmState == .Pulling {
                hmState = .Refeshing
                print("刷新中")
            }
        }
    }
    
    
    
    //设置视图
    private func setupUI(){
        //设置颜色
        backgroundColor = UIColor.orangeColor()
        //添加控件
        addSubview(messageLabel)
        addSubview(activityView)
        addSubview(pullImageView)
        
        //添加约束
        //取消translatesAutoresizingMaskIntoConstraints
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        activityView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: activityView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: activityView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        pullImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))

    }
    
    
    
    //懒加载控件
    private lazy var messageLabel: UILabel = {
    
        let label = UILabel()
        label.text = "正常"
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(15)
        return label
    }()
    //菊花
    private lazy var activityView: UIActivityIndicatorView = UIActivityIndicatorView()
    //箭头
    private lazy var pullImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //KVO移除
    deinit{
    
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    
    }
}

extension WLRefreshControl: UIScrollViewDelegate{
    func scrollViewDidScrollToTop(scrollView: UIScrollView) {
        
    }

}
